import { forwardRef, useEffect, useState } from "react";
import { Popup, TreeSelect, ConfigProvider } from '@antmjs/vantui'
import useInitAction from "@/hooks/useInitAction";
import { handleGetOrderTime } from '@/common/service';
import { View, Text, Image } from "@tarojs/components";
import arrowIcon from '@/assets/images/list-arrow.png'
import closeIcon from '@/assets/images/close-icon.png'
import selectIcon from '@/assets/images/select.png';
import './acceptDialog.scss'
import { IResponseSuccess } from "@/typing";
import { RESPONSE_CODE } from "@/common/config";
import dayjs from 'dayjs'

interface IAcceptDialog {
    show: boolean;
    handlePopStatus: (status) => void;
    handleConfirm: (acceptStartTime, acceptEndTime) => void;
}
interface ITimeListChild {
    text: string;
    id: number;
    title: string
}
interface ITimeList {
    text: string;
    children: Array<ITimeListChild>
}
// add props here

const AcceptDialog: React.FC<IAcceptDialog> = forwardRef((props, ref) => {
    const [callTimeText, setCallTimeText] = useState('立即通话')

    const { show, handlePopStatus, handleConfirm } = props;
    const [dateShow, setDateShow] = useState(false)
    const { bottomSafeHeight } = useInitAction();
    const [acceptStartTime,setAcceptStartTime]= useState(0)
    const [acceptEndTime,setAcceptEndTime]= useState(0)
    const [timeList, setTimeList] = useState<Array<ITimeList>>([])
    const [state, changeState] = useState({
        mainActiveIndex: 0,
        activeId: 1,
    })

    const setState = (newState) => {
        changeState({
            ...state,
            ...newState,
        })
    }

    const onClickNav = ({ detail }) => {
        setState({
            mainActiveIndex: detail.index || 0,
        })
    }

    const onClickItem = ({ detail }) => {
        const activeId = state.activeId === detail.id ? null : detail.id
        if (activeId === 1) {
            setCallTimeText('立即通话')
            setAcceptStartTime(0);
            setAcceptEndTime(0);
        } else {
            const timeArr = detail.text.split(' - ')
            // console.log(timeArr)
            const startTimeString = `${detail.title} ${timeArr[0]}`
            const endTimeString = `${detail.title} ${timeArr[1]}`
            const startTime = dayjs(startTimeString).unix()
            const endTime = dayjs(endTimeString).unix()
            const callText = `${timeList[state.mainActiveIndex].text} ${detail.text}`
            setAcceptStartTime(startTime)
            setAcceptEndTime(endTime)
            setCallTimeText(callText)

        }

        setState({
            activeId,
        })
        setDateShow(false)
    }
    const handleGetOrderTimeList = async () => {
        const timeRes = await handleGetOrderTime() as IResponseSuccess<any>
        if (timeRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
            if (timeRes.data.code === RESPONSE_CODE.SUCCESS) {
                const timeData = timeRes.data.data
                const today = dayjs();
                const tomorrow = today.add(1, 'day');


                let todayChildren
                let timeChildren



                const result = Object.keys(timeData).map(date => {
                    const dateKey = dayjs(date);

                    let text;

                    if (dateKey.isSame(today, 'day')) {
                        text = '今天';
                        todayChildren = timeData[date].map((time, index) => {
                            return {
                                text: time,
                                id: index + 1,
                                title: date
                            }
                        })
                        timeChildren = timeData[date].map((time, index) => {
                            return {
                                text: time,
                                id: index + 1,
                                title: date
                            }
                        })

                    } else if (dateKey.isSame(tomorrow, 'day')) {
                        const week = ['日', '一', '二', '三', '四', '五', '六'];
                        text = `明天周${week[dateKey.day()]}`; // 获取明天的星期几
                        timeChildren = timeData[date].map((time, index) => {
                            return {
                                text: time,
                                id: todayChildren.length + 1 + index,
                            }
                        })
                    }
                    return {
                        text: text,
                        children: timeChildren
                    };
                });
                setTimeList(result)
            }
        }
    }
    useEffect(() => {
        if (show) {
            handleGetOrderTimeList()
        }

        return () => {

        };
    }, [show]);

    return <>
        <Popup show={show} position="bottom" closeOnClickOverlay={true} onClickOverlay={() => handlePopStatus(false)} overlay={true} safeAreaInsetBottom={false} style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '84rpx' }}>
            {
                dateShow ? <View className="pt-44px box-border relative">
                    <View className="w-full text-center text-#161618 text-34px font-bold">选择通话时间</View>
                    <Image src={closeIcon} className="w-36px h-36px absolute top-34px right-36px " onClick={() => setDateShow(false)}></Image>
                    <View className="mt-94px px-50px box-border">
                        <ConfigProvider themeVars={{ treeSelectItemHeight: '90rpx', treeSelectNavItemPadding: '27rpx', sidebarSelectedBorderColor: '#fff' }}>
                            <TreeSelect
                                height={560}
                                items={timeList}
                                mainActiveIndex={state.mainActiveIndex}
                                activeId={state.activeId}
                                onClickNav={onClickNav}
                                onClickItem={onClickItem}
                                selectedIcon={selectIcon}
                            />
                        </ConfigProvider>

                    </View>
                </View> : <View className="pt-56px  box-border">
                    <View className=" text-#161618 text-32px font-bold box-border pl-40px pr-44px flex items-center justify-between">
                        <Text >通话时间</Text>
                        <View className="flex items-center" onClick={() => setDateShow(true)}>
                            <Text>{callTimeText}</Text>
                            <Image src={arrowIcon} className="w-19px h-30px ml-16px"></Image>
                        </View>
                    </View>
                    <View className="mt-34px box-border pl-40px pr-44px text-28px text-#666 leading-46px">用户会收到通话时间通知，请在约定的时间段内拨通电话。</View>
                    <View className="pl-32px pr-48px mt-72px box-border flex items-center justify-between">
                        <View className="w-312px h-92px box-border flex items-center justify-center text-30px font-bold bg-#F5F5F5 text-#333333" onClick={() => handlePopStatus(false)}>取消</View>
                        <View className="w-312px h-92px box-border flex items-center justify-center text-30px font-bold bg-#8232E8 text-#fff" onClick={()=>handleConfirm(acceptStartTime,acceptEndTime)}>确定</View>

                    </View>
                </View>
            }

        </Popup>
    </>

})
export default AcceptDialog